<!-- src/views/product/ProductView.vue -->
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { productApi } from '@/api/product-api'
// import { fileApi } from '@/api/file-api'
import type { Product } from '@/type/product'
import type PageIn from '@/type/page-in'
import { Plus } from '@element-plus/icons-vue'
import AddProductDialog from '@/components/AddProductDialog.vue'
import AsyncImage from '@/components/AsyncImage.vue'
// 分页数据
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0,
})

// 搜索条件
const searchForm = ref({
  name: '',
  category: '',
  status: '',
})

// 商品列表数据
const productList = ref<Product[]>([])


// 加载状态
const loading = ref(false)

// 控制添加商品对话框显示
const showAddDialog = ref(false)

// 当前编辑的商品
const currentEditProduct = ref<Product | null>(null)

// 打开添加商品对话框
const handleAddProduct = () => {
  currentEditProduct.value = null
  showAddDialog.value = true
}

// 添加商品成功回调
const handleAddSuccess = (product: Product) => {
  // 重新加载商品列表
  fetchProductList()
  if (currentEditProduct.value) {
    ElMessage.success(`商品 "${product.title}" 更新成功`)
  } else {
    ElMessage.success(`商品 "${product.title}" 添加成功`)
  }
}


// 获取商品列表
const fetchProductList = async () => {
  loading.value = true

  try {
    // 构造分页参数
    const pageParams: PageIn<never> = {
      page: pagination.value.currentPage,
      size: pagination.value.pageSize,
    }

    // 调用API获取商品列表
    const response = await productApi.list(pageParams)

    // 更新商品列表和分页信息
    productList.value = (response.data || []) as Product[]

    pagination.value.total = response.total || 0

  } catch (error) {
    ElMessage.error('获取商品列表失败')
    console.error('获取商品列表失败:', error)
  } finally {
    loading.value = false
  }
}


// 搜索商品
const handleSearch = () => {
  pagination.value.currentPage = 1
  fetchProductList()
}

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    name: '',
    category: '',
    status: '',
  }
  pagination.value.currentPage = 1
  fetchProductList()
}

// 处理分页变化
const handlePageChange = (page: number) => {
  pagination.value.currentPage = page
  fetchProductList()
}

// 处理页面大小变化
const handleSizeChange = (size: number) => {
  pagination.value.pageSize = size
  pagination.value.currentPage = 1
  fetchProductList()
}

// 编辑商品
const handleEditProduct = (row: Product) => {
  currentEditProduct.value = { ...row }
  showAddDialog.value = true
}

// 删除商品
const handleDeleteProduct = (row: Product) => {
  ElMessageBox.confirm(`确定要删除商品 "${row.title}" 吗？`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        // 使用 productApi.delete(id) 删除商品
        if (row.id) {
          await productApi.delete(row.id)
        } else {
          ElMessage.error('商品ID无效，无法删除')
        }
        ElMessage.success('删除成功')
        await fetchProductList()
      } catch (error) {
        ElMessage.error('删除失败')
        console.error('删除商品失败:', error)
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 组件挂载时获取数据
onMounted(() => {
  fetchProductList()
})
</script>

<template>
  <div class="product-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="商品名称">
              <el-input v-model="searchForm.name" placeholder="请输入商品名称" clearable />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <div class="search-buttons">
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="handleReset">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleAddProduct">
        <el-icon><Plus /></el-icon>
        添加商品
      </el-button>
    </div>

    <!-- 商品列表 -->
    <el-card class="table-card">
      <el-table :data="productList" v-loading="loading" stripe style="width: 100%">
        <el-table-column prop="id" label="商品ID" width="80" />
        <el-table-column prop="coverAddr" label="商品封面" min-width="140">
          <template #default="scope">
            <AsyncImage :image-key="scope.row.coverAddr"  style="width: 80px; height: 80px; border-radius: 4px;"/>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="商品名称" min-width="140" />

        <el-table-column prop="price" label="价格(元)" width="100">
          <template #default="scope"> ¥{{ scope.row.price.toFixed(2) }} </template>
        </el-table-column>
        <el-table-column prop="stockpile" label="库存" width="80" />

        <el-table-column prop="createTime" label="创建时间" width="120" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEditProduct(scope.row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="handleDeleteProduct(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑商品对话框 -->
    <AddProductDialog
      v-model="showAddDialog"
      :edit-product="currentEditProduct"
      @success="handleAddSuccess"
    />
  </div>
</template>

<style scoped>
.product-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-start;
}

.table-card {
  margin-bottom: 20px;
}

.search-buttons {
  display: flex;
  justify-content: flex-start;
  gap: 10px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
